package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.bean.ClassInfo;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.widget.ItemGroup;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ViewConditionsActivity extends AppCompatActivity implements ItemGroup.ItemOnClickListener {

    /*final String setUrl = "http://10.0.2.2:8080/timetable/setConditions";
    final String findUrl = "http://10.0.2.2:8080/timetable/findConditions";*/
    final String setUrl = HttpUtils.headerUrl+"timetable/setConditions";
    final String findUrl = HttpUtils.headerUrl+"timetable/findConditions";
    private static final String TAG = "ViewConditionsActivity";
    private int checkNum_view_classify = 0;
    private int checkNum_checkWay = 0;
    private int checkNum_semester = 0;
    private int checkNum_week = 0;
    private int checkNum = 0;
    private Context mContext;
    private ItemGroup viewClassifyIG, checkWayIG, semesterIG, weekIG;
    private Button backBtn;
    private Button submitBtn;
    private TextView result_tv;
    private SharedPreferences sharedPreferences;
    private String userName;
    private String[] viewclassifyItems;
    private String[] checkWayItems = {"按日查看","按周查看"};
    private String[] semesterItems;
    private String[] weekItems;
    private String checkSemester;
    JSONArray semesterJson;
    JSONObject teacherMsgJson;
    JSONObject currentWeekJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_conditions_set);
        mContext = this;
        initView();
        //传递数据
        /*Intent intent = getIntent();
        intent.getStringExtra("carid");
        intent.getStringExtra("cityname");*/
        //初始化数据
        sharedPreferences = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        userName = sharedPreferences.getString("userName", "");
        if (userName.equals("")) {
            viewclassifyItems = new String[]{"全部"};
            checkNum_view_classify = 0;
        } else {
            viewclassifyItems = new String[]{"全部","我的"};
        }
        findConditionsByPost();
        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });
        submitBtn = findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (!userName.equals("")&&userName!=null)
                    setConditionsByPost();
                //返回数据
                /*Intent intent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("newMsg", "ddd");
                intent.putExtras(bundle);
                ViewConditionsActivity.this.setResult(1,intent);*/
                finish();
            }
        });

    }

    private void updateStatus(View v, String userName) {
    }

    private void initView() {
        viewClassifyIG = (ItemGroup) findViewById(R.id.select_view_classify_ig);
        checkWayIG = (ItemGroup) findViewById(R.id.select_checkWay_ig);
        semesterIG = (ItemGroup) findViewById(R.id.select_semester_ig);
        weekIG = (ItemGroup) findViewById(R.id.select_week_ig);
        result_tv = findViewById(R.id.result_txt);
        viewClassifyIG.setItemOnClickListener(this);
        checkWayIG.setItemOnClickListener(this);
        semesterIG.setItemOnClickListener(this);
        weekIG.setItemOnClickListener(this);
    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {
            case R.id.select_view_classify_ig:
                //Toast.makeText(mContext, "点击了课表展示", Toast.LENGTH_SHORT).show();
                //final String[] items1 = {"我的","全部"};
                String title1 = "选择课表展示";
                showSingleAlertDialogNoBtn(v, viewclassifyItems, title1, 1);
                break;
            case R.id.select_checkWay_ig:
                //final String[] items2 = {"按日查看","按周查看"};
                String title2 = "选择查看方式";
                showSingleAlertDialogNoBtn(v, checkWayItems, title2, 2);
                break;
            case R.id.select_semester_ig:
                //final String[] items3 = {"2014_2015_1", "2014_2015_2", "2015_2016_1", "2015_2016_2", "2016_2017_1", "2016_2017_2", "2017_2018_1", "2017_2018_2"};
                String title3 = "选择学期";
                showSingleAlertDialogNoBtn(v, semesterItems, title3, 3);
                break;
            case R.id.select_week_ig:
                //final String[] items4 = {"第一周", "第二周"};
                String title4 = "选择周数";
                showSingleAlertDialogNoBtn(v, weekItems, title4, 4);
                break;
        }
    }

    // 信息列表提示框
    private AlertDialog showListAlertDialog;

    public void showListAlertDialog(View view, final String[] items, String title) {
        //final String[] items = {"Struts2","Spring","Hibernate","Mybatis","Spring MVC"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(title);
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int index) {
                Toast.makeText(ViewConditionsActivity.this, items[index], Toast.LENGTH_SHORT).show();
                showListAlertDialog.dismiss();
            }
        });
        showListAlertDialog = alertBuilder.create();
        showListAlertDialog.show();
    }


    // 单选提示框
    private AlertDialog singleAlertDialog;

    public void showSingleAlertDialog(View view, final String[] items, String title) {
        //final String[] items = {"Struts2","Spring","Hibernate","Mybatis","Spring MVC"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(title);

        //alertBuilder.set
        alertBuilder.setSingleChoiceItems(items, checkNum, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int index) {
                Toast.makeText(ViewConditionsActivity.this, items[index], Toast.LENGTH_SHORT).show();
                checkNum = index;
            }
        });
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                //TODO 业务逻辑代码

                // 关闭提示框
                singleAlertDialog.dismiss();
            }
        });
        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO 业务逻辑代码

                // 关闭提示框
                singleAlertDialog.dismiss();
            }
        });
        singleAlertDialog = alertBuilder.create();
        singleAlertDialog.show();
    }

    private AlertDialog singleAlertDialogNoBtn;

    public void showSingleAlertDialogNoBtn(View view, final String[] items, String title, final int thisCheckNumClassify) {

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(title);
        switch (thisCheckNumClassify) {
            case 1:
                checkNum = checkNum_view_classify;
                break;
            case 2:
                checkNum = checkNum_checkWay;
                break;
            case 3:
                checkNum = checkNum_semester;
                break;
            case 4:
                checkNum = checkNum_week;
                break;
        }

        alertBuilder.setSingleChoiceItems(items, checkNum, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int index) {
                Toast.makeText(ViewConditionsActivity.this, items[index], Toast.LENGTH_SHORT).show();
                checkNum = index;
                switch (thisCheckNumClassify) {
                    case 1:
                        checkNum = index;
                        checkNum_view_classify = index;
                        viewClassifyIG.setText(items[index]);
                        break;
                    case 2:
                        checkNum = index;
                        checkNum_checkWay = index;
                        checkWayIG.setText(items[index]);
                        break;
                    case 3:
                        checkNum = index;
                        checkNum_semester = index;
                        semesterIG.setText(items[index]);
                        break;
                    case 4:
                        checkNum = index;
                        checkNum_week = index;
                        weekIG.setText(items[index]);
                        break;
                }
                singleAlertDialogNoBtn.dismiss();
            }
        });
        singleAlertDialogNoBtn = alertBuilder.create();
        singleAlertDialogNoBtn.show();
    }

    /**
     * post请求网络
     *
     * @param view
     */
    Handler handler = new Handler() {
        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(ViewConditionsActivity.this, (String)msg.obj, 0).show();
            parseConditionsJSON((String)msg.obj);
        }
    };

    public void findConditionsByPost() {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(findUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    String data = "username=" + URLEncoder.encode(userName);
                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", data.length() + "");

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data.getBytes());
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    private void parseConditionsJSON(String jsonData) {

        try {

            JSONObject jsonObj = new JSONObject(jsonData);
            // Getting JSON Array node
            semesterJson = jsonObj.getJSONArray("semester");
            teacherMsgJson = jsonObj.getJSONObject("teachermsg");
            currentWeekJson = jsonObj.getJSONObject("currentWeek");
            //教师登录时
            if (teacherMsgJson.length() != 0) {
                checkSemester = teacherMsgJson.getString("semesterName");
                checkNum_week = teacherMsgJson.getInt("weekNum");
                checkNum_view_classify = teacherMsgJson.getInt("viewContional");
                checkNum_checkWay = teacherMsgJson.getInt("checkWay");
                //教师登录却不在本学期
                if (currentWeekJson.getString("weekid").equals("notInClassWeek")) {
                    checkSemester = "不选择学期";
                    checkNum_week = 0;
                    weekItems = new String[]{"第0周"};
                }
            } else {
                //教师未登录，却不在本学期
                if (currentWeekJson.getString("weekid").equals("notInClassWeek")) {
                    checkSemester = "不选择学期";
                    checkNum_week = 0;
                    weekItems = new String[]{"第0周"};
                } else {
                    //教师未登录 当前学期 当前周
                    checkSemester = currentWeekJson.getString("semesterName");
                    checkNum_week = currentWeekJson.getInt("weekNum") - 1;
                }

            }
            semesterItems = new String[semesterJson.length()+1];
            for (int i = 0; i < semesterJson.length(); i++) {
                JSONObject jsonObjectTemp = semesterJson.getJSONObject(i);
                String semesterStr = jsonObjectTemp.getString("semesterName");
                semesterItems[i] = semesterStr;
            }
            semesterItems[semesterJson.length()] = "不选择学期";
            for (int i = 0; i < semesterItems.length; i++) {
                if (checkSemester.equals(semesterItems[i])) {
                    checkNum_semester = i;
                    int allweekNum = semesterJson.getJSONObject(i).getInt("weekQuantity");
                    weekItems = new String[allweekNum];
                    for (int j = 0; j < allweekNum; j++) {
                        int tempWeekNum = j + 1;
                        weekItems[j] = "第" + tempWeekNum + "周";
                    }
                    break;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler setHandler = new Handler() {
        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(ViewConditionsActivity.this, (String)msg.obj, 0).show();
        }
    };

    public void setConditionsByPost() {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(setUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    String data = "username=" + URLEncoder.encode(userName) + "&viewClassify="
                            + checkNum_view_classify + "&checkWay="+checkNum_checkWay+"&semesterName="
                            +URLEncoder.encode(semesterItems[checkNum_semester])+"&weekid="+(checkNum_week+1);

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", data.length() + "");

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data.getBytes());
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        setHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}


